#ifndef LISTENER_H
#define LISTENER_H
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include "Packet.h"
#include "Session.h"
#include "Room.h"
using boost::asio::ip::tcp;
using namespace boost::asio;

class Listener
{
public:
	Listener(io_service& io_service,const tcp::endpoint& endpoint)
		: io_service_(io_service),acceptor_(io_service, endpoint)
	{
		SharedSession newSession(new Session(io_service_));
		acceptor_.async_accept(newSession->socket(),
			boost::bind(&Listener::handle_accept, this, newSession,	boost::asio::placeholders::error));
	}

	void handle_accept(SharedSession session,
		const boost::system::error_code& error)
	{
		if (!error)
		{
			session->start();
			if (session->isValid()) 
			{
				Room::getInstance().join(session);
				cout<<"joined to room."<<endl;
			}
			SharedSession newSession(new Session(io_service_));
			acceptor_.async_accept(newSession->socket(),
				boost::bind(&Listener::handle_accept, this, newSession,
				boost::asio::placeholders::error));
		}
	}

private:
	boost::asio::io_service& io_service_;
	tcp::acceptor acceptor_;
};
#endif